package com.hujinwen.esay.t1160;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by joe on 2020/3/17
 * <p>
 * 1160测试题
 */
public class Test_1160 {

    /**
     * 版本1，自己思考得出的结果
     * <p>
     * * 速度慢
     * * 内存消耗大
     */
    static class Function1 {
        public int countCharacters(String[] words, String chars) {
            int resultCount = 0;

            for (String word : words) {
                final List<Character> characters = makeCharList(chars);
                boolean isMaster = true;
                for (char c : word.toCharArray()) {
                    if (!characters.remove(Character.valueOf(c))) {
                        isMaster = false;
                        break;
                    }
                }

                if (isMaster) {
                    resultCount += word.length();
                }

            }

            return resultCount;
        }

        private List<Character> makeCharList(String chars) {
            final List<Character> charList = new ArrayList<>();

            for (char c : chars.toCharArray()) {
                charList.add(c);
            }

            return charList;
        }
    }

    /**
     * 版本2，参考别人的答案理解后写出
     * <p>
     * * 速度够快，
     * * 内存占用依旧过大
     */
    static class Function2 {
        public int countCharacters(String[] words, String chars) {
            int resultCount = 0;

            final int[] map = new int[26];
            for (char c : chars.toCharArray()) {
                map[c - 'a']++;
            }

            final int[] cache = new int[26];
            a:
            for (String word : words) {
                Arrays.fill(cache, 0);
                for (char c : word.toCharArray()) {
                    final int index = c - 'a';
                    if (++cache[index] > map[index]) {
                        continue a;
                    }
                }
                resultCount += word.length();
            }

            return resultCount;
        }
    }


    public static void main(String[] args) {
        final Function2 test = new Function2();
        final int result = test.countCharacters(new String[]{"hello", "world", "leetcode"}, "welldonehoneyr");
        System.out.println(result);

        char a = 'a';
        char b = 'b';
        System.out.println(b - a);

    }

}


